package com.example.studentdemo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.studentdemo.entity.Account;
import com.example.studentdemo.entity.Task;
import com.example.studentdemo.exception.CustomerException;
import com.example.studentdemo.mapper.SubjectMapper;
import com.example.studentdemo.mapper.SubjectStudentMapper;
import com.example.studentdemo.mapper.TaskMapper;
import com.example.studentdemo.service.TaskService;
import com.example.studentdemo.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class TaskServiceImpl implements TaskService {
    @Resource
    private TaskMapper taskMapper;

    @Resource
    private SubjectMapper subjectMapper;

    @Resource
    private SubjectStudentMapper subjectStudentMapper;

    @Override
    public List<Task> selectAll(Task task) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomerException("未登录");
        }

        // 根据用户角色添加查询条件
        String role = currentUser.getRole();
        if ("TEACHER".equals(role)) {
            // 教师只能查看自己创建的课程的任务
            return taskMapper.selectByTeacherId(currentUser.getId());
        } else if ("STUDENT".equals(role)) {
            // 学生只能查看自己参加的课程的任务
            return taskMapper.selectByStudentId(currentUser.getId());
        }
        // 管理员没有限制
        return taskMapper.selectAll(task);
    }

    @Override
    public void add(Task task) {
        // 检查任务名称是否已存在
        Task dbTask = taskMapper.selectByName(task.getName());
        if (dbTask != null) {
            throw new CustomerException("任务名称已存在");
        }
        // 检查状态是否合法
        if (!isValidStatus(task.getStatus())) {
            throw new CustomerException("任务状态不合法，只能是待开始、进行中或已结束");
        }
        taskMapper.insert(task);
    }

    @Override
    public void update(Task task) {
        // 检查是否存在该任务
        Task dbTask = taskMapper.selectById(task.getId());
        if (dbTask == null) {
            throw new CustomerException("任务不存在");
        }
        // 检查任务名称是否已被其他任务使用
        Task dbTaskByName = taskMapper.selectByName(task.getName());
        if (dbTaskByName != null && !dbTaskByName.getId().equals(task.getId())) {
            throw new CustomerException("任务名称已被使用");
        }
        // 检查状态是否合法
        if (StrUtil.isNotBlank(task.getStatus()) && !isValidStatus(task.getStatus())) {
            throw new CustomerException("任务状态不合法，只能是待开始、进行中或已结束");
        }
        taskMapper.updateById(task);
    }

    @Override
    public void deleteById(Integer id) {
        taskMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(List<Task> taskList) {
        for (Task task : taskList) {
            this.deleteById(task.getId());
        }
    }

    @Override
    public PageInfo<Task> selectPage(Integer pageNum, Integer pageSize, Task task) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomerException("未登录");
        }

        // 根据用户角色添加查询条件
        String role = currentUser.getRole();
        if ("TEACHER".equals(role)) {
            // 教师只能查看自己创建的课程的任务
            PageHelper.startPage(pageNum, pageSize);
            List<Task> taskList = taskMapper.selectByTeacherId(currentUser.getId());
            return PageInfo.of(taskList);
        } else if ("STUDENT".equals(role)) {
            // 学生只能查看自己参加的课程的任务
            PageHelper.startPage(pageNum, pageSize);
            List<Task> taskList = taskMapper.selectByStudentId(currentUser.getId());
            return PageInfo.of(taskList);
        }
        // 管理员没有限制
        PageHelper.startPage(pageNum, pageSize);
        List<Task> taskList = taskMapper.selectAll(task);
        return PageInfo.of(taskList);
    }

    @Override
    public Task selectById(Integer id) {
        return taskMapper.selectById(id);
    }

    @Override
    public List<Task> selectBySubjectId(Integer subjectId) {
        return taskMapper.selectBySubjectId(subjectId);
    }

    // 验证任务状态是否合法
    private boolean isValidStatus(String status) {
        return "待开始".equals(status) || "进行中".equals(status) || "已结束".equals(status);
    }
}